package blogic;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import otherModels.SlideImage;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.widget.ImageView;
import dbmodels.Photo;

public class Operations {

	public static List<SlideImage> getPhotos(Context context, BusinessLogic bl,
			UUID albumId, UUID userId) {

		List<Photo> photos = bl.GetPhotosFromAlbum(albumId, userId);
		List<SlideImage> images = new ArrayList<SlideImage>();

		SlideImage im;
		for (Photo photo : photos) {
			im = new SlideImage();
			im.setImage(convertFromBytes(context, photo.getBytes()));
			im.setName(photo.getName());
			im.setPermision(photo.getPermision());
			images.add(im);
		}

		return images;
	}

	public static ImageView convertFromBytes(Context context, byte[] bytes) {

		Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		ImageView image = new ImageView(context);
		image.setImageBitmap(bmp);

		return image;
	}

	public static Bitmap convertFromBytesInBitmap(Context context,
			byte[] bytes, int size) {
		if (size == 0)
			size = 400;
		return resizeImage(
				BitmapFactory.decodeByteArray(bytes, 0, bytes.length), size);
	}

	private static Bitmap resizeImage(Bitmap bitmap, int newSize) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		int newWidth = 0;
		int newHeight = 0;

		if (width > height) {
			newWidth = newSize;
			newHeight = (newSize * height) / width;
		} else if (width < height) {
			newHeight = newSize;
			newWidth = (newSize * width) / height;
		} else if (width == height) {
			newHeight = newSize;
			newWidth = newSize;
		}

		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);

		return resizedBitmap;
	}

}
